﻿using Max.PH5_2011A.Domain;
using Max.PH5_2011A.IRespository;
using Max.PH5_2011A.IService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2011A.Service
{
    public class CityService : BaseService<CityModel>, ICityService
    {
        ICityRespository _respository;
        public CityService(ICityRespository respository, IUnitOfWork unitOfWork) : base(respository, unitOfWork)
        {
            _respository = respository;
        }


        /// <summary>
        /// 城市递归
        /// </summary>
        /// <returns></returns>
        public List<dynamic> GetCityRecursion()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            var data = _respository.Query().ToList();
            var list = this.RecursionCity(data, 1);
            watch.Stop();
            Console.WriteLine($"===================={watch.ElapsedMilliseconds}====================");
            return list;
        }

        //递归城市列表
        private List<dynamic> RecursionCity(List<CityModel> data, int id)
        {
            var list = data.Where(x => x.PId == id);

            List<dynamic> result = new();

            list.ToList().ForEach(x =>
            {
                var t = RecursionCity(data, x.Id);
                result.Add(new
                {
                    name = x.Name,
                    id = x.Id,
                    children = t != null && t.Count > 0 ? t : null
                });
            });
            return result;
        }

    }
}
